package miiteen.customsportal.Api;


import com.sun.deploy.net.HttpResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import miiteen.core.result.ResultMessage;
import miiteen.core.result.ResultMessageTool;
import miiteen.customsportal.ct.beans.CTDataType;
import miiteen.customsportal.ct.service.CTDataTypeService;
import miiteen.customsportal.data.beans.DataInfo;
import miiteen.customsportal.data.beans.DataInfoImage;
import miiteen.customsportal.data.service.DataInfoService;


import miiteen.data.beans.PageBounds;
import miiteen.hr.department.beans.HrDepartmentInfo;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;



import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 综合资料
 *
 */
@Api(tags = "综合资料")
@RestController
@RequestMapping("/Api/DataInfo")
@CrossOrigin
public class DataInfoApiController {

    @Autowired
    private DataInfoService dataInfoService;

    @Autowired
    private CTDataTypeService ctDataTypeService;

//    private final static String HOME_PATH = DownloadTemplateServlet.class.getResource("/").getPath();
//    private final static String DOWNLOAD_TEMP_FILE = HOME_PATH.subSequence(0, HOME_PATH.indexOf("WEB-INF")) + "file/";
    @GetMapping("findAllType")
    @ApiOperation("获取所有综合资料类型")
    public ResultMessage<Object> getTypeList(){

       List<CTDataType> list=ctDataTypeService.findListByMap();

        if(list!=null&&list.size()>0){
            return ResultMessageTool.Success("success",list);
        }
        return ResultMessageTool.Error("未找到相关信息");
    }

/*
    @GetMapping("findByList")
    @ApiOperation("列表页面")
    public ResultMessage<Object> GetList(){

        List<DataInfo> list=dataInfoService.findListByMap();


        if(list!=null&&list.size()>0){
            return ResultMessageTool.Success("success",list);
        }
        return ResultMessageTool.Error("未找到相关信息");
    }*/



    @GetMapping("findByTimeList")
    @ApiOperation("返回发布时间为当天或之前的数据")
    public ResultMessage<Object> GetByTimeList(@ApiParam(name = "typeId", value = "综合资料类型Id") @RequestParam String typeId){
        Map<String,Object> map=new HashMap<>();
        map.put("typeId",typeId);

        List<DataInfo> list=dataInfoService.findListByMap(map);

        if(list!=null&&list.size()>0){
            return ResultMessageTool.Success("success",list);
        }
        return ResultMessageTool.Error("未找到相关信息");
    }

    @GetMapping("findById")
    @ApiOperation("详情页面")
    public ResultMessage<Object> GetOne(@ApiParam(name = "id", value = "综合资料Id") @RequestParam String  id,@ApiParam(name = "typeId", value = "综合资料类型Id") @RequestParam String  typeId){
        Map<String,Object> restMap=new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

        if(id!=null&&!"".equals(id)){
            boolean isSpecial= ctDataTypeService.findById(Long.parseLong(typeId)).getYlzd2()==1?true:false;
            Map<String,Object> map=new HashMap<>();
            if(!isSpecial){//判断是不是特殊上传那种
                DataInfo dataInfo=dataInfoService.findById(Long.valueOf(id));
                if(dataInfo!=null ){
                    restMap.put("dataInfo",dataInfo);
                    map.put("publishTimePrevious",sdf.format(dataInfo.getPublishTime()));
                    map.put("dataTypeId",dataInfo.getDataTypeId());
                    DataInfo previousOne=dataInfoService.findListByMapPreviousNext(map);
                    if(previousOne!=null){
                        restMap.put("previousOne",previousOne);
                    }
                    map.clear();
                    map.put("publishTimeNext",sdf.format(dataInfo.getPublishTime()));
                    map.put("dataTypeId",dataInfo.getDataTypeId());
                    DataInfo nextOne=dataInfoService.findListByMapPreviousNext(map);
                    if(nextOne!=null){
                        restMap.put("nextOne",nextOne);
                    }
                    return  ResultMessageTool.Success("查询成功",restMap);
                }
            }else if(!"".equals(typeId)&&typeId!=null){
             map.put("typeId",typeId);
             map.put("catalogCategory",id);
             List<DataInfo> infoList=dataInfoService.findByCategory(map);
             restMap.put("infoList",infoList);
             map.put("catalogCategoryPrevious",id);
             DataInfo previousOne=dataInfoService.findPreviousNextCategory(map);
             if(previousOne!=null){
                    restMap.put("previousOne",previousOne);
             }
             map.clear();
             map.put("catalogCategory",id);
             map.put("catalogCategoryNext",id);
             map.put("typeId",typeId);
             DataInfo nextOne=dataInfoService.findPreviousNextCategory(map);
             if(nextOne!=null){
                    restMap.put("nextOne",nextOne);
             }
             if(infoList.size()>0){
                 return  ResultMessageTool.Success("查询成功",restMap);
             }else{
                 return  ResultMessageTool.Error("查询失败，未找到该目录下的资料数据");
             }
            }
            return  ResultMessageTool.Error("未找到该信息！");
        }

        return ResultMessageTool.Error("未接收到参数信息");
    }

    @ApiOperation("下载资料")  //ResponseEntity<>
    @RequestMapping(value="/download",method = RequestMethod.GET)
    public void download(@ApiParam(name = "filePath", value = "list里面的image")  String imagePath, HttpServletResponse response) throws IOException {

        try {
            response.reset();
            response.setContentType("application/ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(imagePath, "UTF-8"));
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            URL p = getClass().getProtectionDomain().getCodeSource().getLocation();
            String url = p.toString();
            String path = "";
            String filePath =imagePath;
            String[] urls = url.split("/");
            int count=0;
            for(int i=0;i<urls.length;i++){
                if(urls[i].equals("target")){
                    count=i;
                }
            }
            if (url.indexOf("WEB-INF") == -1) {
                for(int i=0;i<count-1;i++){
                    path = path+urls[i+1]+"/";
                }
                path =path+"src/main/webapp" + filePath;
            } else {
                path = url.substring(0, url.indexOf("WEB-INF")).replace("file:/", "") + filePath;
            }
            File file = new File(path);
            DataInputStream in = new DataInputStream(
                    new FileInputStream(file));
            //输出流
            OutputStream out = response.getOutputStream();
            //输出文件
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.close();
            in.close();
        }catch (Exception e){
            e.printStackTrace();
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "*");
            try {
                OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
                String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";
                writer.write(data);
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        /*URL p=getClass().getProtectionDomain().getCodeSource().getLocation();
       String url=p.toString();
       String path="";
       String filePath=dataInfoImage.getImage();
       String[] urls=url.split("/");
       if(url.indexOf("WEB-INF")==-1){
         path=  urls[1]+ "/" +urls[2]+"/src/main/webapp"+filePath;
       }else{
           path=url.substring(0,url.indexOf("WEB-INF")).replace("file:/","")+filePath;
       }
        File file = new File(path);
        String name=file.getName();
        try {
            byte[] bytes  = FileUtils.readFileToByteArray(file);
            return bytes;
           // return HttpUtil.download(name, bytes);
        } catch (Exception e) {
            return  e.getMessage().getBytes();
          //  return HttpUtil.download("error.txt", e.getMessage().getBytes());
        }
*/
    }



    @GetMapping("findDepts")
    @ApiOperation("获取全部部门")
    public ResultMessage<Object> getDepts(){

        List<DataInfo> list=dataInfoService.findAllDept();
        List<DataInfo> newList=new ArrayList<>();
       Map<Long,String> map=new HashMap<>();
        for (int i = 0; i <list.size() ; i++) {
            DataInfo dataInfo=list.get(i);
            map.put(dataInfo.getParentId(),dataInfo.getParentDepartName());
        }
        for(Map.Entry<Long,String>  entry : map.entrySet()){

            long parentId = entry.getKey();
            String department = entry.getValue();
            DataInfo newDataInfo=new DataInfo();
            List<HrDepartmentInfo> departMentInfoList=new ArrayList<>();
            int count=0;
            for (int i = 0; i <list.size() ; i++) {
                DataInfo dataInfo=list.get(i);
                if(dataInfo.getParentId()==parentId){
                    count++;
                    HrDepartmentInfo hrDepartmentInfo=new HrDepartmentInfo();
                    hrDepartmentInfo.setId( dataInfo.getId());
                    hrDepartmentInfo.setDepartmentName(dataInfo.getDepartment());
                    newDataInfo.setParentDepartName(dataInfo.getParentDepartName());
                    if(count>1){
                        departMentInfoList.add(hrDepartmentInfo);
                    }else{
                        departMentInfoList=new ArrayList<>();
                        departMentInfoList.add(hrDepartmentInfo);
                    }
                    newDataInfo.setDepartMentInfoList(departMentInfoList);
                }
            }
            newList.add(newDataInfo);
        }
        if(newList.size()>0){
            return ResultMessageTool.Success("查询成功",newList);
        }else{
            return ResultMessageTool.Error("查询失败");
        }

    }

    @GetMapping("findByLimits")
    @ApiOperation("通过条件搜索综合资料")
    public ResultMessage<Object> findByLimits(@ApiParam(name = "page", value = "页码，非必传")@RequestParam Integer page
             ,@ApiParam(name = "typeId", value = "类型Id")@RequestParam String typeId
            ,@ApiParam(name = "startTime", value = "起始时间，类型为字符串") @RequestParam String startTime
    ,@ApiParam(name = "endTime", value = "起始时间，类型为字符串") @RequestParam String endTime
            ,@ApiParam(name = "deptId", value = "部门ID") @RequestParam String deptId,
                                              @ApiParam(name = "title", value = "关键字（按标题搜索）") @RequestParam String title){
        Map<String,Object> resultMap=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
       // Map<String,Object> countMap=new HashMap<>();
        boolean isSpecial=false;
        if(!"".equals(typeId)){
            map.put("typeId",typeId);
           // countMap.put("typeId",typeId);
            isSpecial= ctDataTypeService.findById(Long.parseLong(typeId)).getYlzd2()==1?true:false;
        }

        List<DataInfo> list=new ArrayList<>();
        if(!"".equals(startTime)){
            map.put("startTime",startTime);
        }
        if(!"".equals(endTime)){
            map.put("endTime",endTime);
        }
        if(!"".equals(deptId)){
            map.put("deptId",Long.valueOf(deptId));
        }
        if(!"".equals(title)){
            map.put("title",title);
        }
        map.put("publishTime","发布时间");
       if(isSpecial){//如果是资料上传
           List<DataInfo> count=dataInfoService.findListByMap(map);
           if(page>=1){
               map.put("pageBounds",page);
           }
           list=dataInfoService.findAllCategory(map);
           resultMap.put("total",count.size());
       }else{
//           List<DataInfo> count=dataInfoService.findListByMap(countMap);
//           resultMap.put("total",count.size());

           map.put("order","order by a.publishTime desc");
           List<DataInfo> count=dataInfoService.findListByMap(map);
           PageBounds pageBounds = new PageBounds();
           if (page > 0 ) {
               pageBounds.setPageSize(10);
               pageBounds.setPageNum(page);
               list= dataInfoService.findListByMap(map,pageBounds);
           }else {
               list=dataInfoService.findListByMap(map);
           }
           resultMap.put("total",count.size());
       }
        resultMap.put("list",list);
        if(list.size()>0){
            return ResultMessageTool.Success("查询成功",resultMap);
        }else{
            return ResultMessageTool.Error("查询失败");
        }


    }


}
